package com.ruoyi.web.controller.littleRedBook;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.littleRedBook.domain.pojo.Coupon;
import com.ruoyi.littleRedBook.domain.pojo.ReceiveRecord;
import com.ruoyi.littleRedBook.service.CouponService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 优惠券表 前端控制器
 * </p>
 *
 * @author
 * @since
 */
@RestController
@RequestMapping("/api/coupon")
public class CouponController {

    @Autowired
    private CouponService couponService;

    /**
     * 新增优惠券
     */
    @PostMapping
    public AjaxResult add(@RequestBody Coupon coupon) {
        return AjaxResult.success(couponService.save(coupon));
    }

    /**
     * 修改优惠券
     */
    @PutMapping
    public AjaxResult edit(@RequestBody Coupon coupon) {
        return AjaxResult.success(couponService.updateById(coupon));
    }

    /**
     * 删除优惠券
     */
    @DeleteMapping("/{couponIds}")
    public AjaxResult remove(@PathVariable Long[] couponIds) {
        return AjaxResult.success(couponService.removeByIds(Arrays.asList(couponIds)));
    }

    /**
     * 查询优惠券详情
     */
    @GetMapping("/{couponId}")
    public AjaxResult getInfo(@PathVariable Long couponId) {
        return AjaxResult.success(couponService.getById(couponId));
    }

    /**
     * 查询优惠券列表(管理端)
     */
    @GetMapping("/list/management")
    public AjaxResult listNotDeleted() {
        return AjaxResult.success(couponService.listNotDeleted());
    }
    /**
     * 查询优惠券列表(用户端)
     */
    @GetMapping("/list/user")
    public AjaxResult list() {
        return AjaxResult.success(couponService.getValidCoupons());
    }

    /**
     * 回收站
     */
    @GetMapping("/list/rubbish")
    public AjaxResult listDeleted() {
        return AjaxResult.success(couponService.listDeleted());
    }


    /**
     * 领取优惠券接口
     * @param userId 用户ID
     * @param couponId 优惠券ID
     * @return 统一响应结果
     */
    @PostMapping("/receive")
    public AjaxResult receiveCoupon(@RequestParam Long userId, @RequestParam Long couponId) {
        try {
            ReceiveRecord record = couponService.receiveCoupon(userId, couponId);
            return AjaxResult.success("领取成功", record);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}
